﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace Database
{
    public class ActiveRecord
    {
        #region Fields

        private readonly string connectionString;

        #endregion

        #region Properties

        public Dictionary<string, object> Parameters { get; set; }

        #endregion

        #region Creation

        public ActiveRecord(string connectionString)
        {
            this.connectionString = connectionString;
            this.Parameters = new Dictionary<string, object>();
        }

        #endregion

        public bool Insert(string storedProcedure)
        {
            // Houston, we have a problem...
            if (this.Parameters.Count == 0)
                throw new ArgumentNullException("Parameters cannot be empty in an insert statement");

            using (var connection = new SqlConnection(connectionString))
            using (var command = connection.CreateCommand())
            {
                connection.Open();
                command.CommandType = CommandType.StoredProcedure;

                // set command text to the stored procedure we recieve as parameter
                command.CommandText = storedProcedure;


                // for each parameter specified, add entry to cmd parameters
                foreach (var parameter in this.Parameters)
                {
                    command.Parameters.AddWithValue(parameter.Key, parameter.Value);
                }

                // clear parameters, there's no need to save them
                this.Parameters.Clear();

                // execute query
                int rowCount = command.ExecuteNonQuery();

                if (rowCount > 0)
                    return true;
                else
                    return false;
            }
        }

        public void AddParameters(object obj)
		{
            foreach (var prop in obj.GetType().GetProperties())
            {
                this.Parameters.Add("@"+prop.Name, prop.GetValue(obj, null));
            }
		}
    }

}
